using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Mvc;

namespace MyTesting
{
	internal sealed class CheckFilters<TController>
		where TController : Controller, new()
	{
		private readonly TController _controller;

		public CheckFilters()
		{
			_controller = new TController();
		}


		public TAttribute GetAttribute<TAttribute>(Expression<Action<TController>> action)
			where TAttribute : Attribute
		{
			var body = action.Body as MethodCallExpression;
			if (body == null)
				throw new InvalidOperationException("Expression must be a method call.");

			IEnumerable<Type> constantExpressions = from exp in body.Arguments.OfType<ConstantExpression>()
			                                        select exp.Type;

			Type[] types = constantExpressions.ToArray();
			MethodInfo methodInfo = _controller.GetType().GetMethod(body.Method.Name, types);

			return (TAttribute) Attribute.GetCustomAttribute(methodInfo, typeof (TAttribute));
		}
	}
}